package models

import (
	"errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"time"
)

// MerchantTemp 临时商户表
type MerchantTemp struct {
	Merchant
}

// MerchantTempExistByID 通过id判断是否存在
func MerchantTempExistByID(id int) (bool, error) {
	var merchant MerchantTemp
	db.Select("id").Where("id = ?", id).First(&merchant)
	if merchant.ID > 0 {
		return true, nil
	}
	return false, errors.New("此商户不存在")
}

// MerchantTempExistByMobile 通过mobile判断是否存在
func MerchantTempExistByMobile(mobile string) (bool, error) {
	var merchant MerchantTemp
	db.Select("id").Where("merchant_mobile = ?", mobile).First(&merchant)
	if merchant.ID > 0 {
		return true, nil
	}
	return false, errors.New("此代理不存在")
}

// MerchantTempDeleteById 通过id删除商户
func MerchantTempDeleteById(id interface{}) error {
	err := db.Delete(&MerchantTemp{}, "id = ?", id).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("通过id删除商户失败: id:%d err:%v", id, err)
		return errors.New("此代理不存在")
	}
	return nil
}

// MerchantTempInfoById 商户通过id获取信息
func MerchantTempInfoById(id interface{}) (*Merchant, error) {
	var merchant MerchantTemp
	err := db.Where("id = ?", id).First(&merchant).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此代理不存在: id:%d err:%v", id, err)
		return nil, errors.New("此代理不存在")
	}

	if merchant.ID == 0 {
		return nil, errors.New("此商户不存在")
	}

	merchant.CreatedAt = time.Now()
	merchant.UpdatedAt = time.Now()
	merchant.ID = 0

	return &merchant.Merchant, nil
}

// MerchantTempInfoAdd 添加临时商户信息
func MerchantTempInfoAdd(merchantMobile, merchantTypeId, merchantShopTypeId, agentId, SalesmenId, mainMerchantId interface{}) (map[string]string, error) {
	merchant := &MerchantTemp{
		Merchant{
			MerchantMobile:     cast.ToString(merchantMobile),
			MerchantTypeID:     cast.ToInt(merchantTypeId),
			MerchantShopTypeID: cast.ToInt(merchantShopTypeId),
			AgentID:            cast.ToInt(agentId),
			SalesmenID:         cast.ToInt(SalesmenId),
			MainMerchantId:     cast.ToInt(mainMerchantId),
		},
	}

	err := db.Create(merchant).Error
	if err != nil {
		logrus.WithError(err).Errorf("创建商户失败: merchant:%v err:%v", merchant, err)
		return nil, errors.New("创建商户失败")
	}

	return map[string]string{
		"id": cast.ToString(merchant.ID),
	}, nil
}

// MerchantTempShopAdd 添加商户门店信息
func MerchantTempShopAdd(id int, merchantName, merchantAddress, merchantAddressId, merchantFrontPhoto, merchantCheckstandPhoto, merchantIndoorPhoto, merchantRelationCertPhoto string, MerchantRangeCode, merchantLongitude, merchantLatitude interface{}) error {
	merchant := MerchantTemp{
		Merchant{
			MerchantRangeCode:         cast.ToInt(MerchantRangeCode),
			MerchantName:              merchantName,
			MerchantAddress:           merchantAddress,
			MerchantAddressId:         cast.ToInt(merchantAddressId),
			MerchantFrontPhoto:        merchantFrontPhoto,
			MerchantCheckstandPhoto:   merchantCheckstandPhoto,
			MerchantIndoorPhoto:       merchantIndoorPhoto,
			MerchantRelationCertPhoto: merchantRelationCertPhoto,
			MerchantLongitude:         cast.ToFloat64(merchantLongitude),
			MerchantLatitude:          cast.ToFloat64(merchantLatitude),
		},
	}
	err := db.Model(&MerchantTemp{}).Where("id = ?", id).Updates(&merchant).Error
	if err != nil {
		logrus.WithError(err).Errorf("添加商户门店信息失败: merchant:%v err:%v", merchant, err)
		return errors.New("添加商户门店信息失败")
	}

	return nil
}

// MerchantTempLegalAdd 添加商户法人信息
func MerchantTempLegalAdd(legalPersonName, legalPersonIdcard, legalPersonIdcardPhotoFront, legalPersonIdcardPhotoBack, legalPersonIdcardHold, legalContactIdCardNo, legalContactName, legalContactMobile string, id, legalContactType, legalPersonIdcardValidityBegin, legalPersonIdcardValidityEnd interface{}) error {
	err := db.Model(&MerchantTemp{}).Where("id = ?", id).Updates(map[string]interface{}{
		"legal_person_name":                  legalPersonName,
		"legal_person_idcard":                legalPersonIdcard,
		"legal_person_idcard_photo_front":    legalPersonIdcardPhotoFront,
		"legal_person_idcard_photo_back":     legalPersonIdcardPhotoBack,
		"legal_person_idcard_hold":           legalPersonIdcardHold,
		"legal_person_idcard_validity_begin": legalPersonIdcardValidityBegin,
		"legal_person_idcard_validity_end":   legalPersonIdcardValidityEnd,
		"legal_contact_type":                 legalContactType,
		"legal_contact_name":                 legalContactName,
		"legal_contact_id_card_no":           legalContactIdCardNo,
		"legal_contact_mobile":               legalContactMobile,
	}).Error

	if err != nil {
		return errors.New("添加商户法人信息失败")
	}

	return nil
}

// MerchantTempMerchantLicenseInfoAdd 添加商户营业执照信息
func MerchantTempMerchantLicenseInfoAdd(licensePhoto, licenseName, licenseCode, licenseStartDate, licenseEndDate, licenseAddress, activityId, id interface{}) error {
	err := db.Model(&MerchantTemp{}).Where("id = ?", id).Updates(map[string]interface{}{
		"license_photo":      licensePhoto,
		"license_name":       licenseName,
		"license_code":       licenseCode,
		"license_start_date": licenseStartDate,
		"license_end_date":   licenseEndDate,
		"license_address":    licenseAddress,
		"activity_id":        activityId,
	}).Error

	if err != nil {
		logrus.WithError(err).Errorf(
			"添加商户营业执照信息:id:%s licensePhoto:%s licenseName:%s licenseCode:%s licenseStartDate:%s licenseEndDate:%s licenseAddress:%s err:%v",
			id, licensePhoto, licenseName, licenseCode, licenseStartDate, licenseEndDate, licenseAddress, err)
		return errors.New("添加商户法人信息失败")
	}

	return nil
}

// MerchantTempBankAdd 添加商户结算信息
func MerchantTempBankAdd(id, settleAccountType, settleBankcardFrontPic, settleBankcardNo, settleBankMobile, settleSubbranchCode, settleIdcardNo,
	settleIdcardStartDate, settleIdcardEndDate, settleIdcardFrontName, settleIdcardBackName, settleAuthName, settleName interface{}) (map[string]interface{}, error) {
	err := db.Model(&MerchantTemp{}).Where("id = ?", id).Updates(map[string]interface{}{
		"settle_account_type":      settleAccountType,
		"settle_bank_card_photo":   settleBankcardFrontPic,
		"settle_bankcard_no":       settleBankcardNo,
		"settle_bank_phone":        settleBankMobile,
		"ld_settle_subbranch_code": settleSubbranchCode,
		"settle_idcard_no":         settleIdcardNo,
		"settle_idcard_start_date": settleIdcardStartDate,
		"settle_idcard_end_date":   settleIdcardEndDate,
		"settle_idcard_front_name": settleIdcardFrontName,
		"settle_idcard_back_name":  settleIdcardBackName,
		"settle_auth_name":         settleAuthName,
		"settle_name":              settleName,
	}).Error

	if err != nil {
		return nil, errors.New("添加商户法人信息失败")
	}

	return map[string]interface{}{
		"id": cast.ToString(id),
	}, nil
}
